package com.wiken.gatewayservice.filter;

import com.wiken.servicecommon.common.Code;
import com.wiken.servicecommon.common.TokenUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {

    @Value("${property.gateway.whiteList}")
    private ArrayList<String> whiteList;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String requestPath = exchange.getRequest().getPath().value();
        log.info(requestPath);

        boolean isWhitePath = hasWhiteList(requestPath);
        if (isWhitePath) return chain.filter(exchange);

        ServerHttpResponse response = exchange.getResponse();

        //判断请求头中是否有token，没有token不能放行
        List<String> authorizationList = exchange.getRequest().getHeaders().get("Authorization");

        if (authorizationList == null || authorizationList.size() <= 0 || authorizationList.get(0).trim().isEmpty()) {

            response.setRawStatusCode(Code.ERROR_AUTHORIZATION_NULL);
            return response.setComplete();
        }

        try {
            Claims claims = TokenUtil.parseToken(authorizationList.get(0));
            //判断token是否存在于jwt中，不存在不能放行
            if (claims == null || claims.get("userId", String.class) == null) {
                response.setRawStatusCode(Code.ERROR_AUTHORIZATION_NULL);
                return response.setComplete();
            }
        } catch (Exception e) {
            response.setRawStatusCode(Code.ERROR_AUTHORIZATION_NULL);
            return response.setComplete();
        }

        //token存在jwt，放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    public boolean hasWhiteList(String requestPath){
        for (String whitePath : whiteList){
            if(whitePath.matches(requestPath)) return true;
        }

        return false;
    }
}
